//index.js
//获取应用实例
import{ShareModel} from '../../model/share'
var share = new ShareModel()

const app = getApp()

Component({
  properties: {
    model:Object
  },
  data: {
    maskHidden:true,
    imagePath:'',
    shareBanner:'',
    avatar:'',
    qrcode:'',
    width:0,
    height:0
  },
  
  methods: {
    canvasIdErrorCallback: function (e) {
    console.error(e.detail.errMsg)
  },
  createNewImg: function() {
    var that = this;
    // console.log(that.data.qrcode)
    var context = wx.createCanvasContext('mycanvas',that);
    context.setFillStyle("#ffffff")
    context.fillRect(0, 0, 670, 959)

    //分享中间图
    var path1 = that.data.shareBanner
    console.log(path1)
    context.drawImage(path1, 0, 0, 670, 800);
    //将模板图片绘制到canvas,在开发工具中drawImage()函数有问题，不显示图片
    //分割线
    var path2 = "/static/iconS1.png";
    //头像
    var path3 = that.data.avatar;
    //二维码
    var path4 = that.data.qrcode;
    // var path5 = "/static/payBottom.png";
    //不知道是什么原因，手机环境能正常显示
    context.save(); // 保存当前context的状态

    //绘制品牌头像
    // context.drawImage(path3, 20, 547, 70, 80);
    context.save(); // 保存
    context.beginPath();
    context.arc(50 + 30, 50 + 820, 50, 0, Math.PI * 2, false);
    context.clip();
    context.drawImage(path3, 30, 820, 100, 100)
    context.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 可以继续绘制
    context.draw();
    //绘制商品对应的品牌名称
    context.setFontSize(25);
    context.setFillStyle('#000000');
    context.setTextAlign('left');
    context.fillText(app.globalData.userInfo.nickName+"  邀请你", 145, 835);
    context.setFontSize(22);
    context.setFillStyle('#333333');
    context.setTextAlign('left');
    context.fillText("一起来投票支持", 145, 875);
    context.setFontSize(22);
    context.setFillStyle('#333333');
    context.setTextAlign('left');
    context.fillText("优雅前行乘风破浪的姐姐吧。", 145, 915);
    context.stroke();
    //绘制扫码即可查看商品更多信息
    context.drawImage(path4, 530, 810, 110,110); //二维码
    context.setFontSize(18);
    context.setFillStyle('#000000');
    context.setTextAlign('left');
    context.fillText('长按扫码投票', 530, 945);
    context.stroke();
    //绘制商品
    // context.drawImage(path5, 25, 600, 26, 24);
    // context.stroke();
    
    // context.stroke();
    //绘制中间分割线
    // context.drawImage(path2, -8, 455, 390, 45);
    context.draw(true, setTimeout(function() {
      //将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: 670,
        height: 959,
        destWidth: 2010,
        destHeight: 2877,
        canvasId: 'mycanvas',
        success: function(res) {
          var tempFilePath = res.tempFilePath;
          console.log(res)
          that.setData({
            imagePath: tempFilePath,
          });
        },
        fail: function(res) {
          console.log(res);
        }
      },that);
    }, 200));
  },

  //点击保存到相册
  savePoster: function() {
    var that = this
    console.log(that.data.imagePath)
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imagePath,
      success(res) {
        wx.showModal({
          content: '海报已保存到相册',
          showCancel: false,
          confirmText: '好的',
          confirmColor: '#333',
          success: function(res) {
            if (res.confirm) {
              console.log('999999')
              console.log('用户点击确定');
              /* 该隐藏的隐藏 */
              that.setData({
                maskHidden: true
              })
            }
          },
          fail: function(res) {
            console.log(11111)
          }
        })
      },
      fail(res) {
        // wx.showToast({
        //   title: '保存失败',
        //   icon: 'none',
        // })
        if (res.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || res.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
          // 这边微信做过调整，必须要在按钮中触发，因此需要在弹框回调中进行调用
          wx.showModal({
            title: '提示',
            content: '需要您授权保存相册',
            showCancel: false,
            success: modalSuccess => {
              wx.openSetting({
                success(settingdata) {
                  console.log("settingdata", settingdata)
                  if (settingdata.authSetting['scope.writePhotosAlbum']) {
                    wx.showModal({
                      title: '提示',
                      content: '获取权限成功,再次点击图片即可保存',
                      showCancel: false,
                    })
                  } else {
                    wx.showModal({
                      title: '提示',
                      content: '获取权限失败，将无法保存到相册哦~',
                      showCancel: false,
                    })
                  }
                },
                fail(failData) {
                  console.log("failData", failData)
                },
                complete(finishData) {
                  console.log("finishData", finishData)
                }
              })
            }

          })
        }
      }
    })
  },
  //点击生成
  formSubmit: function(e) {
    var that = this;
    share.qrCode(
      that.properties.model.id+";;"+app.globalData.userInfo.id,"pages/vote/list/list"
    ).then(res =>{
      console.log(res);
      const file = wx.getFileSystemManager()
      var img = wx.base64ToArrayBuffer(res.data);  //对数据进行转换操作
      const fileName = wx.env.USER_DATA_PATH + '/share_vote_img.png'
      file.writeFileSync( fileName, img, 'binary')
      this.setData({
        qrcode:fileName
      })
      console.log(this.data.qrcode)
    })
    wx.getSystemInfo({
      success (res) {
        console.log(res)
        // 通过像素比计算出画布的实际大小（330x490）是展示的出来的大小
        that.setData({
          width : 375 * res.pixelRatio,
          height : 667 * res.pixelRatio
         });
      }
    })
    wx.getImageInfo({
      src: that.properties.model.shareBanner,
      success:res =>{
        this.setData({
         shareBanner : res.path
        });
        console.log(res)
      },
      fail:res =>{ 
        console.log(res)
      }
    })
    let avatarUrl = ''
    if(app.globalData.userInfo.avatarUrl.indexOf("https") == -1){
      avatarUrl = app.globalData.userInfo.avatarUrl.replace('http','https')
    }else{
      avatarUrl =app.globalData.userInfo.avatarUrl
    }
    wx.getImageInfo({
      src: avatarUrl,
      success:res =>{
        this.setData({
         avatar : res.path
        });
        console.log(res)
      },
      fail:res =>{ 
        console.log(res)
      }
    })
    this.setData({
      maskHidden: false
    });
    wx.showToast({
      title: '海报生成中...',
      icon: 'loading',
      duration: 1000
    });
    setTimeout(function() {
      wx.hideToast()
      that.createNewImg();
      that.setData({
        maskHidden: false
      });
    }, 1000)
  },
}
})
